/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gestion;

import java.awt.Color;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import java.util.GregorianCalendar;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;
import impresos.DatosToImprimir;
import impresos.ImpVale;
import otros.Fecha;
import impresos.ImpVenta;
import otros.Util;
import tablasSql.Articulos;
import tablasSql.Clientes;
import tablasSql.ConsultaBD;
import tablasSql.FacturasAlbaranes;
import tablasSql.Sql;
import tablasSql.Stock;

/**
 *
 * @author FERRETERIA
 */
public class FTPV extends javax.swing.JInternalFrame {
    
    private final static Logger log = Logger.getLogger(FTPV.class);
    
//---------------------------------------------------------------------------RELOJ    
    public class Reloj implements Runnable { 

        private String dia, mes, año, hora, minutos, segundos; 
        private Calendar calendario = new GregorianCalendar(); 
        Thread hilo; 
        
        public Reloj() { //Constructor 
            hilo = new Thread(this); 
            hilo.start(); 
        } //fin constructor 

        @ Override 
        public void run() { 
            Thread ct = Thread.currentThread(); 
            while (ct == hilo) { 
                try { 
                    actualiza(); 
                    lblTime.setText("<html><center>" + dia + "/" + mes + "/" + año + " " + hora + ":" + minutos + ":" + segundos); 

                    Thread.sleep(100); 
                } catch (InterruptedException ex) { 
                    log.error(ex.getMessage()); 
                } 
            } 
        } 
        
        public void actualiza() { 
            Date fechaHoraActual = new Date(); 
            calendario.setTime(fechaHoraActual); 

            hora = String.valueOf(calendario.get(Calendar.HOUR_OF_DAY)); 
            minutos = calendario.get(Calendar.MINUTE) > 9 ? "" + calendario.get(Calendar.MINUTE) : "0" + calendario.get(Calendar.MINUTE); 
            segundos = calendario.get(Calendar.SECOND) > 9 ? "" + calendario.get(Calendar.SECOND) : "0" + calendario.get(Calendar.SECOND);
            dia = calendario.get(Calendar.DATE) > 9 ? "" + calendario.get(Calendar.DATE) : "0" + calendario.get(Calendar.DATE); 
            mes = calendario.get(Calendar.MONTH)+1 > 9 ? "" + (calendario.get(Calendar.MONTH)+1) : "0" + (calendario.get(Calendar.MONTH)+1); 
            año = calendario.get(Calendar.YEAR) > 9 ? "" + calendario.get(Calendar.YEAR) : "0" + calendario.get(Calendar.YEAR); 
        }        
    }
    
//---------------------------------------------------------------------------RELOJ    

//---------------------------------------------------------------------TABLA LISTENER         
//  Actualizo las variables de los calculos de la lista de articulos
    public class MiCellEditorListener implements CellEditorListener {
        
        public void editingStopped(ChangeEvent e) {
            int fila = tabla.getSelectedRow();
            int colum = tabla.getSelectedColumn();
                 
            // veo si estan los campos rellenos de la fila
            boolean todo = true;
            for (int i = 3; (i < 7) && todo; i++)
                if ((tabla.getValueAt(fila, i) == null) || 
                        (tabla.getValueAt(fila, i).toString().equals("")))
                     todo = false;   
                    
            if (todo) { 
                boolean hayar = false;     // variable que me determina que se ha cambiado algo 
                float bCantidad = Float.parseFloat(tabla.getValueAt(fila, 3).toString().replace(",", "."));
                float bPrecio = Float.parseFloat(tabla.getValueAt(fila, 4).toString().replace(",", "."));
                float bDescuento = Float.parseFloat(tabla.getValueAt(fila, 6).toString().replace("%", "").replace(",",".").trim());
                float bMargen = Float.parseFloat(tabla.getValueAt(fila, 5).toString().replace("%", "").replace(",", ".").trim());
                // compruebo si se ha modificado algo de la fila seleccionada
                if (cantidad != bCantidad) {
                    cantidad = bCantidad;
                    hayar = true;                    
                }
                if (precio != bPrecio) {
                    precio = bPrecio;
                    hayar = true;
                }
                if (descuento != bDescuento) {
                    descuento = bDescuento;
                    hayar = true;
                }
                tabla.setValueAt(descuento + "%", fila, 6);
                
                
                if (margen != bMargen) {
                    margen = bMargen;
                    hayar = true;
                }
                tabla.setValueAt(margen + "%", fila, 5);

                if (hayar) { 
                    if (tabla.getValueAt(fila, 7) != null) // compruebo si tiene un total anterior para eliminarlo
                        totalVenta -= total;
                    calcular();
                    tabla.setValueAt(total,fila,7);
                    if ((tabla.getValueAt(fila, 1) == null) && (tabla.getRowCount()-1 == fila)) {
                        //((DefaultTableModel)tabla.getModel()).addRow(new Object [] {tabla.getRowCount()+1,null,null,null, null,null,null,null});
                        nuevaLinea();
                        tabla.scrollRectToVisible(tabla.getCellRect(tabla.getRowCount()-1, 0, true));
                        if (!bGuardar.isEnabled())
                            activarBotones(true);   
                        txtBuscar.requestFocus();
                    }
                    resetValores();
                }
            }
        }
        
        @Override
        public void editingCanceled(ChangeEvent ce) {
            //log.info("no hago naa");
        }
    }
//---------------------------------------------------------------------TABLA LISTENER    
    
    //private int descuento = 0;          // descuento producto
    private float descuento = 0;
    private float margen = 0;             // margen
    private float cantidad = 1;           
    private float precio = 0;           // costo
    private float totalVenta = 0;      // la suma de precio de todos los productos
    private float total = 0;           // precio del producto cantidad * costo - descuento
    private String memoria = "";
    private boolean buscar = false;
    private int filaEdit;               // fila q se editando
    private int columEdit;              // columna q se esta editando
    private boolean guardar = true;     // factura nueva
    private float descCliPie = 0;
    private float descCliLinea = 0;
    private float margenCli = 0;
    private int numCopiasFact;
    private int numCopiasAlbaranes;
    private int numTicket;
    private String numIdImp = null;            // se usa para asignar un numero de factura y continuar con el.
    private int pasada = 1;             // variable pa controlar que solo se opeta una vez en la tabla
    private boolean cambioEstado = false; 
    private boolean cargoDesdeOtraVentana = false;
    private float entrego;             // cantidad que entrego el cliente para pagar 
    private String fechaCrea = "";          // pa modificar la fecha de creacion cuando la fecha es menor que crea
            
    public JTextField getTxtBuscar () {
        return txtBuscar;
    }
   
    private void mapeo() {
        ActionMap mapaAccion = this.getActionMap();
        InputMap map = this.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        //negro
        KeyStroke ctrl_n = KeyStroke.getKeyStroke(KeyEvent.VK_N,Event.CTRL_MASK);
        map.put(ctrl_n , "ctrl_n");
        mapaAccion.put("ctrl_n",CTRL_N());
        //reset
        KeyStroke ctrl_r = KeyStroke.getKeyStroke(KeyEvent.VK_R,Event.CTRL_MASK);
        map.put(ctrl_r , "ctrl_r");
        mapaAccion.put("ctrl_r",CTRL_R());
        
        //cajon
        KeyStroke cajon = KeyStroke.getKeyStroke(KeyEvent.VK_F4,0);
        map.put(cajon , "cajon");
        mapaAccion.put("cajon",F4());
        //nueva linea
        KeyStroke linea = KeyStroke.getKeyStroke(KeyEvent.VK_F3,0);
        map.put(linea , "linea");
        mapaAccion.put("linea",F3());
        
        //ale
        KeyStroke ticket = KeyStroke.getKeyStroke(KeyEvent.VK_F5,0);
        map.put(ticket , "ticket");
        mapaAccion.put("ticket",F5());
        //Onan
        KeyStroke factura = KeyStroke.getKeyStroke(KeyEvent.VK_F6,0);
        map.put(factura , "factura");
        mapaAccion.put("factura",F6());
        //Tino
        KeyStroke guardar = KeyStroke.getKeyStroke(KeyEvent.VK_F7,0);
        map.put(guardar , "guardar");
        mapaAccion.put("guardar",F7());
        //Juan
        KeyStroke reset = KeyStroke.getKeyStroke(KeyEvent.VK_F8,0);
        map.put(reset , "reset");
        mapaAccion.put("reset",F8());
        
        KeyStroke f9 = KeyStroke.getKeyStroke(KeyEvent.VK_F9,0);
        map.put(f9 , "f9");
        mapaAccion.put("f9",F9());
        
    } 
    
    public AbstractAction CTRL_N(){
        return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {
                        if (((cbTipoTicket.getSelectedIndex()==0) || (cbTipoTicket.getSelectedIndex()==1))
                                && (cbTipoPago.getSelectedIndex()==0) && rbEfectivo.isSelected()) {
                            if ((cbTipoTicket.getSelectedIndex()==0) && (guardar)) {
                                cbTipoTicket.setSelectedIndex(1);
                                cbTipoPago.setSelectedIndex(0);
                            }
                            txtNegro.setVisible(true);
                          
                            if (txtNegro.getText().isEmpty() || txtNegro.getText().equals("0") ) {
                                txtNegro.setText(txtPrecioDigital.getText().replace(",",".").replace("€", "").trim());
                                txtEntrego.requestFocus();        
                            }
                       } 
                    }
                };
    }
    
    public AbstractAction CTRL_R(){
        return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {
                        totalVenta = 0;
                        for (int i = 0; i < tabla.getRowCount(); i++) {
                            if (tabla.getValueAt(i, 2) != null) {
                                cantidad = Float.parseFloat(""+tabla.getValueAt(i, 3));
                                precio = Float.parseFloat(""+tabla.getValueAt(i, 4));
                                margen = Float.parseFloat(tabla.getValueAt(i, 5).toString().replace("%", ""));
                                descuento = Float.parseFloat(tabla.getValueAt(i, 6).toString().replace("%", ""));
                                calcular();
                            }
                        }
                    }
                };
    }
    
    public AbstractAction F3(){
        return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {nuevaLinea();} 
                };
    }
     
    private void nuevaLinea() {
       ((DefaultTableModel)tabla.getModel()).addRow(new Object [] {tabla.getRowCount()+1,null,null,null, null,null,null,null});          
    }
    
    public AbstractAction F4(){
        return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {ImpVenta.abrirCajon();} 
                };
    }
    public AbstractAction F5(){ return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {
                         cbVendedor.setSelectedIndex(0);
                    }    };
    }
    public AbstractAction F6(){ return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {
                        cbVendedor.setSelectedIndex(1);
                    }   };
    }
    public AbstractAction F7(){ return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {
                        cbVendedor.setSelectedIndex(2);
                    }  };
    }
    public AbstractAction F8(){
        return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {
                        cbVendedor.setSelectedIndex(3);
                    }  };
    }
    
    public AbstractAction F9(){
        return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {
                        
                    }  };
    }
    
    //-------------------------------------------------------------------------------construtor
    //-------------------------------------------------------------------------------
    //-------------------------------------------------------------------------------
    public FTPV() {
        Util.setConfiguracionLog(Util.LOG4_FICH);
        initComponents();
        Reloj r = new Reloj();
        r.run();
        
        lblError.setVisible(false);
        pDatosCliente.setVisible(false);
        txtBuscar.requestFocus(true);
         
        CellEditorListener ChangeNotification = new MiCellEditorListener();
        tabla.getDefaultEditor(Integer.class).addCellEditorListener(ChangeNotification);
        tabla.getDefaultEditor(String.class).addCellEditorListener(ChangeNotification);
        tabla.getDefaultEditor(Float.class).addCellEditorListener(ChangeNotification);
        grupo.add(rbCheque);
        grupo.add(rbEfectivo);
        grupo.add(rbTarjeta);
        grupo.add(rbTrans);
        grupo.add(rbVale);
        rbEfectivo.setSelected(true);
        
        resetFTPV();
        mapeo();
    }
    
    private void activarBotones(boolean activar) {
        bGuardar.setEnabled(activar);
        bImprimir.setEnabled(activar);
        if (tabla.getRowCount() > 17)
            bTicket.setEnabled(false);
        else
            bTicket.setEnabled(activar);
    }
    
    private void resetFTPV() {
        activarBotones(false);
        resetValores();
        margen = -0;
       
        getCliente("0");
       
        txtIdFecha.setText(""+new Fecha().getAño());
        initNumTicket(0);
        txtBuscar.requestFocus(true);
        totalVenta = 0;
        mostrarPrecioFinal(totalVenta);
        txtPrecioFinalMano.setText(null);
        txtComentario.setText("");
        borrarTabla();
        guardar = true;
        
        txtFecha.setText("");
        mostrarReloj(true);
        pasada=1;
        numIdImp = null;
        
        chNoOriginal.setSelected(false);
        txtNegro.setText("0");
        txtNegro.setVisible(false);
        txtEntrego.setText("");
        entrego=-1;
        rbEfectivo.setSelected(true);
        
        mostrarDatosCli(false);
        if(tabla.isEditing())
            tabla.editingStopped(null);
        chNoImpDescuento.setSelected(false);
        ColorVendedor();
    }
    
    private void borrarTabla () {
        if(tabla.isEditing())
            tabla.editingStopped(null);
        int tam = tabla.getRowCount();
        for (int i = 0; i < tam; i++) 
            ((DefaultTableModel)tabla.getModel()).removeRow(0);
        if (tabla.getRowCount() == 0)
            ((DefaultTableModel)tabla.getModel()).addRow(new Object[] {1,null,null,null,null,null,null,null});
    }

//---------------------------------------------------------------Tratamiento factura / albaran 
  
    private void initNumTicket (int id) {
        try {
            int idImp = 0;
            int idAño = Integer.parseInt(txtIdFecha.getText());
            String sql = "select idImp, idAno as año from ";
            switch (cbTipoTicket.getSelectedIndex()) {
                case 1:
                    if (id == 0) id = Sql.getMax("id","albaranes where idAno = " + idAño);
                    sql +=  "albaranes where id = " + id;
                    break;
                case 2:
                    if (id == 0) id = Sql.getMax("id","presupuestos where idAno = " + idAño);
                    sql +=  "presupuestos where id = " + id;
                    break;
                case 3:   
                    if (id == 0) id = Sql.getMax("id","fiados where idAno = " + idAño);
                    sql +=  "fiados where id = " + id;
                    break;
                default:
                    if (id == 0) id = Sql.getMax("id","facturas where idAno = " + idAño);
                    sql += "facturas where id = " + id ;
                    break;
            }
                
            ResultSet res = FacturasAlbaranes.getDatos(sql);
            if (res.next()) {
                idImp = (res.getInt("año") == idAño)? res.getInt("idImp") : 0;
            }
            txtIdImp.setValue(idImp);
            txtIdFecha.setText(""+idAño);
            
            numTicket = id;
            cambiarEstadoTicket(false);
        } catch (SQLException ex) {
            log.warn("initNumTicket: " + ex);
        }
    }
    
    private void cambiarEstadoTicket(boolean habilitar) {
        String tipo = habilitar ? "" : cbTipoTicket.getSelectedItem().toString();
        Color color = Util.getColorTicket(tipo);
        txtIdFecha.setBackground(color);
        txtIdImp.setBackground(color);
        lblCant.setBackground(color);
        lblDesc.setBackground(color);
        lblMarg.setBackground(color);
        lblQuitar.setBackground(color);
        lblResetear.setBackground(color);
    }
    
    private void habilitarIdTicket(boolean valor) {
        txtIdImp.setEditable(valor);
        txtIdFecha.setEditable(valor);
    }
    
    public void cargarNumTicket(String id, boolean albaran) {
        cbTipoTicket.setSelectedIndex(albaran ? 1:0);
        numTicket = Integer.parseInt(id);
        cargar();
    }
//------------------------------------------------------------------------------------------------
//---------------------------------------------------------------Tratamiento lista de articulos y precio    
    private void calcular () {
        total = (1.0f+(margen/100.0f))* precio * cantidad * (1.0f-(descuento/100.0f));
        total = Util.redondeo(total,4);
        totalVenta += total;
        mostrarPrecioFinal(totalVenta);
        descuentoPie();
    }
    
    private void mostrarPrecioFinal(Object valor) {
        String precio = Util.getFormatPrecio(valor,2);
        txtPrecioDigital.setText(precio);
        txtPrecioFinal.setText(precio);
        setEntrego();
    }
   
    private void setVarFila(int fila) {
         Object cant = tabla.getValueAt(fila, 3);
         Object prec = tabla.getValueAt(fila, 4);
         Object marg = tabla.getValueAt(fila, 5);
         Object desc = tabla.getValueAt(fila, 6);
         if((cant != null) && (prec != null) && (desc != null) && (marg != null) && 
             !cant.toString().isEmpty() && !prec.toString().isEmpty() && !desc.toString().isEmpty() && !marg.toString().isEmpty()) {
            cantidad = Float.parseFloat(cant.toString());
            precio = Float.parseFloat(prec.toString());
            descuento = Float.parseFloat(desc.toString().replace("%", "").replace(",",".").trim());
            margen = Float.parseFloat(marg.toString().replace("%", "").trim());
            total = Float.parseFloat(tabla.getValueAt(fila, 7).toString());
         }
    }
    
    private void descuentoPie() {
        if ((txtPrecioFinalMano.getText().isEmpty()) || (txtPrecioFinalMano.getText() == null)
                || (txtPrecioFinalMano.getText().equals("0.0"))) {
            try {
                String text = txtDescuentoPie.getText().replace("%", "").trim();
                double desc = Double.parseDouble(text);
                txtDescuentoPie.setText(text + "%");
                txtPrecioDigital.setText(Util.getFormatPrecio(totalVenta - (totalVenta * desc / 100),2));
                setEntrego();
            } catch (Exception e) {;}
        }
    }
    
    private void setPrecioFinal() {
        double precio = 0;
        if ((!txtPrecioFinalMano.getText().isEmpty()) && (txtPrecioFinalMano.getText() != null))
            try {
                precio = Double.parseDouble(txtPrecioFinalMano.getText());
            } catch (Exception e) {
                txtPrecioFinalMano.setText(""+FacturasAlbaranes.PRECIOCERO);
                precio = FacturasAlbaranes.PRECIOCERO;
            }
        if (precio != 0) {
            if (precio == FacturasAlbaranes.PRECIOCERO)
                txtPrecioDigital.setText(Util.getFormatPrecio(0,2));
            else
                txtPrecioDigital.setText(Util.getFormatPrecio(precio,2));
        }
        descuentoPie();
        setEntrego();
    }
    
    private boolean ComprobarEntrego() {
        try {
            entrego = Float.parseFloat(txtEntrego.getText());
            return true;
        } catch (Exception ex) {
            entrego = -1;
            return false;
        }
    }
    private void setEntrego () {
        if ((cbTipoPago.getSelectedIndex()!=0) || (cbTipoTicket.getSelectedIndex() > 1))
            entrego = 0;
        else    //contado
            if (!rbEfectivo.isSelected()) { 
                entrego = Float.parseFloat(txtPrecioDigital.getText().replace(",",".").replace("€",""));
                txtEntrego.setText(""+entrego);
            }
//            else {
//                if(guardar) && entrego{
//                    entrego = -1;
//                    txtEntrego.setText("");
//                }
//            }            
    }
    
    private int getPagoEn() {
        if (cbTipoPago.getSelectedIndex() > 0) {
            return -1;
        }
        else if (rbEfectivo.isSelected())
            return 0;
        else if (rbTarjeta.isSelected())
            return 1;
        else if (rbCheque.isSelected())
            return 2;
        else if (rbTrans.isSelected())
            return 3;      // tranferencia
        else return 4; //vale
    }
    
    private void setPagoEn(int valor) {
        switch (valor) {
            case 1: rbTarjeta.setSelected(true);
                    break;
            case 2: rbCheque.setSelected(true);
                    break;
            case 3: rbTrans.setSelected(true);
                    break;
            case 4: rbVale.setSelected(true);
                    break;
            default: rbEfectivo.setSelected(true);
                    break;
        }
    }
    
    private void resetValores () {
        cantidad = 1;
        txtCantidad.setText(Float.toString(cantidad).replace(".", ",") + "x");
        txtCantidad.setForeground(Color.black);
        descuento = -0;
        if (descCliLinea > 0)
            descuento = descCliLinea;
        //margen = 0;           // esta comentado ya que el margen es para todos los articulos
        if (margenCli > 0)
            margen = margenCli;    
        precio = 0;
    }
//------------------------------------------------------------------------------------------------  
//-------------------------------------------------------------Tratamiento de la ventana de error
    private void mostrarMensajeError (boolean visible, int tipo) {
        switch (tipo) {
            case 1:
                lblError.setText("<html><P ALIGN=center> ¡¡¡¡Error!!!!  Articulo no Existe</P>");         
                break;
            case 2:
                lblError.setText("<html><p align=center> ¡¡Error Formato!!<br> dd/mm/yyyy</p>");
                break;
            case 3:
                lblError.setText("<html><p align=center> ¡¡Error!!<br> No guardado</p>");
                break;
            case 4:
                lblError.setText("<html><p align=center> ¡¡Falta!!<br> Dinero Entregado</p>");
                break;
            case 5:
                float valor = entrego -
                              Float.parseFloat(txtPrecioDigital.getText().replace(",", ".").replace("€",""));
                lblError.setText("<html><p align=center> Devolver <br>"+ Util.getFormatPrecio(valor, 2)+"</p>");
                break;
            
            default:
                lblError.setText("<html><p align=center> ¡¡¡¡Error!!!!<br> Ticket no Existe</p>");
                break;
        }    
        mostrarMensajeError(visible);
    }
    
    private void mostrarMensajeError (boolean visible) {
        lblError.setVisible(visible);
        tabla.setVisible(!visible);
    }
//------------------------------------------------------------------------------------------------
    private void mostrarReloj(boolean valor) {
        pFecha.setVisible(!valor);
        pFecha.setEnabled(!valor);
        lblTime.setVisible(valor);
    }
    
    private void mostrarDatosCli (boolean valor) {
        pDatosCliente.setVisible(valor);
        tabla.setVisible(!valor);
        pProductos.setVisible(!valor);
        if (valor)
           txtCliNombre.requestFocus();
        else
            txtBuscar.requestFocus();      
    }
    
    private void mostrarContado (boolean valor) {
        pPago.setVisible(valor);
        if (guardar) {
            entrego = valor?-1:0;
 //           txtEntrego.setText(valor?"":"0");
        }
        lblDio.setVisible(valor);
        txtEntrego.setVisible(valor);
        txtNumCopias.setText("0");             
        if (!valor) {
            resetNegro();
            txtNumCopias.setText("1"); 
        } else rbEfectivo.setSelected(valor);
    }
//---------------------------------------------------------------------ARTICULOS  
    public void abrirBusquedaArticulo(String valor) {
        buscar = true;
        FListArticulos la = new FListArticulos(this, Util.FTPV, valor);
        this.getParent().add(la);
        Principal.centrarFrame(la);
        la.show();
    }

// Determina que es lo que introduzco y busca el articulo para añadirlo a la lista
    public void añadirArticulo() {
        if (!memoria.equals(txtBuscar.getText()) && buscar) {
            memoria = txtBuscar.getText();
            String criterio = "codigo";
            
            if (tabla.isEditing())
                tabla.editingCanceled(null);
            
            ResultSet art = null; 
            try {
                if (memoria.length() > 6) {
                    criterio = "codigoBarras1";
                    art = Articulos.getArticulo(criterio, txtBuscar.getText());
                    if (!art.next())
                        criterio = "codigoBarras2";
                }
               
                art = Articulos.getArticulo(criterio, txtBuscar.getText());
                if (art.next()) {
                    mostrarMensajeError(false);
                    addArticulo(art);
                    resetValores();
                    buscar = false;
                }
                else {
                    abrirBusquedaArticulo(memoria);
                    //txtBuscar.selectAll();
                    //mostrarMensajeError(true,1);
                }
                activarBotones(true);
            } catch (SQLException ex) {
                    mostrarMensajeError(true,1);
            }
        }
    }
    
//------------------------------------------------------ Articulo a la tabla
    private void addArticulo(ResultSet art) {
        try {
            //tabla.getSelectionModel().clearSelection();  //quita la fila seleccionada
            if (tabla.getCellEditor() != null) {
                tabla.getCellEditor().stopCellEditing();
            }
            
            precio = art.getFloat("PrecioVenta");
            calcular();
            
            verStock(String.valueOf(art.getInt("codigo")), cantidad);
            
            tabla.setValueAt(art.getInt("codigo"), tabla.getRowCount()-1, 1);
            tabla.setValueAt(art.getString("detalle"), tabla.getRowCount()-1, 2);
            tabla.setValueAt(cantidad, tabla.getRowCount()-1, 3);
            tabla.setValueAt(precio, tabla.getRowCount()-1, 4);
            tabla.setValueAt(margen + "%", tabla.getRowCount()-1, 5);
            tabla.setValueAt(descuento + "%", tabla.getRowCount()-1, 6);
            tabla.setValueAt(total, tabla.getRowCount()-1, 7);
            
            DefaultTableModel modeloTabla=(DefaultTableModel)tabla.getModel();
            modeloTabla.addRow(new Object[] {tabla.getRowCount()+1,null,null,null,null,null,null});
            tabla.setModel(modeloTabla);
            tabla.scrollRectToVisible(tabla.getCellRect(tabla.getRowCount()-1, 0, true));
          
            txtBuscar.setText("");
            memoria = "";
            txtBuscar.requestFocus();
            // desactivo boton de ticket xq no puedo imprimir cosas mas largas
            if (tabla.getRowCount() > 17) bTicket.setEnabled(false);
        } catch (SQLException ex) {
            log.error(ex);       
        }
    }
//------------------------------------------------------------------------------
//-------------------------------------------------------------------------CLIENTE    
    public void getCliente(String cli) {
        try {
            ResultSet res = Clientes.getCliente(cli);
            if (res.next()){
                txtCodCliente.setText(cli);
                txtNomComercial.setText(res.getString("nombrecomercial"));
                txtCliNombre.setText(res.getString("nombrecomercial"));
                txtCliDomicilio.setText(res.getString("domicilio"));
                txtCliLocalidad.setText(res.getString("localidad"));
                txtCliCodPostal.setText(res.getString("codigopostal"));
                txtCliFiscal.setText(res.getString("nombrefiscal"));
                txtCliTelefono.setText(res.getString("telefono1"));
                txtCliCIF.setText(res.getString("nif"));
                txtBuscar.requestFocus();
                descCliLinea = res.getInt("descLinea");
                descCliPie = res.getInt("descPie");
                txtDescuentoPie.setText(descCliPie + "%");
                descuentoPie();
                numCopiasFact = res.getInt("copiasfacturas");
                numCopiasAlbaranes = res.getInt("copiasalbaranes");
                setNumCopias();
                margenCli = res.getFloat("margen");
                margen = margenCli;
                descuento = descCliLinea;
                if(guardar) {
                    switch(res.getInt("tipopago")) {
                        case 0:     // factura contado
                            cbTipoTicket.setSelectedIndex(0);
                            cbTipoPago.setSelectedIndex(0);
                            break;
                        case 1:     //factura credito
                            cbTipoTicket.setSelectedIndex(0);
                            cbTipoPago.setSelectedIndex(1);
                            comprobarCredito(res.getFloat("credito"));
                            break;
                        case 2:     //albaran credito
                            cbTipoTicket.setSelectedIndex(1);
                            cbTipoPago.setSelectedIndex(1);
                            comprobarCredito(res.getFloat("credito"));
                            break;
                        case 3:
                            cbTipoTicket.setSelectedIndex(3);
                            break;
                    }
                }
                else {
                    if (cbTipoPago.getSelectedIndex()== 1)
                        comprobarCredito(res.getFloat("credito"));
                }
                    
            }
        } catch (SQLException ex) {
            log.warn(ex);
        }
    }
    
    private void comprobarCredito(float credito){
        try {
            if (credito > 0) {
                String sql = "select round(sum(if(totalmano> 0, totalmano, (1-(descuento/100))*total)),2)";
                sql += " as suma from TABLA where idCliente = " + txtCodCliente.getText();
                sql += " and tipoPago = 1";
                ResultSet resF = FacturasAlbaranes.getDatos(sql.replace("TABLA", FacturasAlbaranes.getTablaSql(0)));
                ResultSet resA = FacturasAlbaranes.getDatos(sql.replace("TABLA", FacturasAlbaranes.getTablaSql(1)));
                float suma = 0;
                if (resF.next())
                    suma += resF.getFloat("suma");
                if (resA.next())
                    suma += resA.getFloat("suma");
                if (suma > credito) {
                    String texto = "El cliente tiene excedido su credito actual de \"" + credito + "€\" con " + suma +"€";
                    JOptionPane.showMessageDialog(this,texto,
                                "Credito", JOptionPane.WARNING_MESSAGE);
                }
            }
        } catch (SQLException ex) {
            log.warn("comprobarCredito(credito): " + ex);
        }
    }
    
    private void guardarTicketCli(int tipo) {
        String [] dato = {""+numTicket, txtCodCliente.getText()};
        Clientes.guardarUltTicket(dato, tipo);
    }
    
    private void setNumCopias() {
        int copias = 0;
        switch(cbTipoTicket.getSelectedIndex()) {
            case 0:
                copias = numCopiasFact;
                break;
            case 1:
                copias = numCopiasAlbaranes;
                if (!txtNegro.getText().isEmpty())
                    copias = 0;
                break;
            case 2:
            case 3:
                copias = 0;
                break;
        }
        if ((copias == 0) && (cbTipoPago.getSelectedIndex()==1) 
                && (cbTipoTicket.getSelectedIndex()!=2))
            copias = 1;
        txtNumCopias.setText(""+copias );
    }
    
//--------------------------------------------------------------------------------    
//-------------------------------------------------------------------------STOCK
    private void verStock (String codigo, float num) {
        float stock = Stock.getStock(codigo);
        if (stock - num <= 0) {
            JOptionPane.showMessageDialog(this,"El stock actual es de " + stock,
                            "Stock", JOptionPane.WARNING_MESSAGE);       
        }
    }

//------------------------------------------------------------------------------
//----------------------------------------------------------------------Datos a imprimir
    private DatosToImprimir getDatosToImprimir() {
        DatosToImprimir d = new DatosToImprimir();
        d.setCliNum(txtCodCliente.getText());
        d.setCliCIF(txtCliCIF.getText());
        d.setCliCodPostal(txtCliCodPostal.getText());
        d.setCliDomicilio(txtCliDomicilio.getText());
        d.setCliLocalidad(txtCliLocalidad.getText());
        d.setCliNomFiscal(txtCliFiscal.getText());
        d.setCliNombre(txtCliNombre.getText());
        d.setCliTelefono(txtCliTelefono.getText());
        if (!chNoImpDescuento.isSelected()) {
            d.setDescPie(!txtDescuentoPie.getText().isEmpty() ? txtDescuentoPie.getText() : "0%");
            d.setPrecioMano(!txtPrecioFinalMano.getText().isEmpty() ? txtPrecioFinalMano.getText() : "0.00");
            d.setEntregado(((cbTipoPago.getSelectedIndex()==0) && 
                        (cbTipoTicket.getSelectedIndex() < 2))? txtEntrego.getText() : null);
        
        }
        else {
            d.setDescPie("0%");
            d.setPrecioMano("0.00");
            d.setEntregado(null);
        }
        
        d.setNumTicket(txtIdFecha.getText()+ "-" + txtIdImp.getText());
        d.setPrecioBruto(txtPrecioFinal.getText());
        d.setTabla(tabla);
        d.setTipoTicket(cbTipoTicket.getSelectedItem().toString());
        if (!txtNegro.getText().isEmpty())
            if (Float.parseFloat(txtNegro.getText()) > 0)
                d.setTipoTicket("Ticket");
        d.setPagoEn(getPagoEn());
        d.setNoOriginal(chNoOriginal.isSelected());
        
        String fecha = new Fecha().getFecha(); 
        if (!guardar || !txtFecha.getText().isEmpty())
            fecha = txtFecha.getText();
        d.setFecha(fecha);
        d.setComentario(txtComentario.getText());
        d.setNumCopias(Integer.parseInt(txtNumCopias.getText()));
        
        
        return d;
    }
    
    private void abrirCajon() {
        if (cbTipoPago.isVisible() && (cbTipoPago.getSelectedIndex() == 0) 
                && !rbTrans.isSelected() && !rbVale.isSelected())
            ImpVenta.abrirCajon();
    }
//------------------------------------------------------------------------------
    public boolean guardar() {
        if (entrego > -1) {
            ConsultaBD.cursorEspera(this);

            String sqlTabla = FacturasAlbaranes.getTablaSql(cbTipoTicket.getSelectedIndex());
            String fecha = (txtFecha.getText().isEmpty())? new Fecha().getFechaSQL()
                                                         : new Fecha(txtFecha.getText()).getFechaSQL();
            String fechaHora = fecha + " " + lblTime.getText().substring(24);
            //--------- datos que se guardaran
            ArrayList<String> v = new ArrayList<String> ();
            
            v.add(fechaHora);   
            if (guardar)
                v.add(fechaHora);                           //fechaCrea
            else
                if (fecha.compareTo(fechaCrea) < 0) {
                // fechaCrea la modificamos para el 347 
                    String msg = txtIdFecha.getText() + "-" + txtIdImp.getText() + 
                            "  cambio de fechaCrea " + fechaCrea + " -> " + fecha; 
                    log.warn(msg);
                    FacturasAlbaranes.cambiarFechaCrea(cbTipoTicket.getSelectedIndex(), fechaHora, numTicket);
                }
                    
            if (cbTipoTicket.getSelectedIndex()==3) // fiados;
                v.add(new Fecha().getFechaSQL());       // fechamodifi
            v.add(txtComentario.getText());
            v.add(txtPrecioFinal.getText().replace("€", "").replace(",",".").trim()); 
            v.add(txtDescuentoPie.getText().equals("") ? "0" : txtDescuentoPie.getText().replace("%", "").trim()); 
            v.add(txtPrecioFinalMano.getText().equals("") ? "0" : txtPrecioFinalMano.getText());
            if ((cbTipoTicket.getSelectedIndex()==0)||(cbTipoTicket.getSelectedIndex()==1)) { // factura, albaran
                v.add(txtNegro.getText().equals("") ? "0" : txtNegro.getText());
                v.add(""+entrego);
                v.add(""+getPagoEn());
            }
             
            v.add(txtCodCliente.getText());
            v.add(""+cbTipoPago.getSelectedIndex());
            v.add(""+cbVendedor.getSelectedIndex());
            //--------------------------------------
            int imp = 0;
            if (guardar) {
                if ((numIdImp != null) && (!numIdImp.isEmpty())) 
                    imp = Integer.parseInt(numIdImp);
                else {
                    imp = Sql.getMax("idImp", sqlTabla + " where idAno = " + txtIdFecha.getText()) + 1;
                    if (imp == -1) 
                        imp = 0;
                }
                v.add(""+imp);
                v.add(""+txtIdFecha.getText());
                numTicket = FacturasAlbaranes.guardar(v.toArray(new String[v.size()]), guardar, cbTipoTicket.getSelectedIndex());
            } else {
                //v.add(txtIdImp.getText());
                v.add(""+numTicket);
                FacturasAlbaranes.guardar(v.toArray(new String[v.size()]), guardar, cbTipoTicket.getSelectedIndex());          
            }

            // cuando cargo borro la lista de articulos
            if (!guardar) 
                FacturasAlbaranes.borrarListArticulos(numTicket, cbTipoTicket.getSelectedIndex());

            if(numTicket != -1) {
                for (int i = 0; i < tabla.getRowCount()-1; i++) {
                    String codigo = null;
                    if ((tabla.getValueAt(i, 1) != null) && !tabla.getValueAt(i,1).toString().isEmpty()) {
                       codigo = tabla.getValueAt(i, 1).toString(); //idArticulo
                       if (cbTipoTicket.getSelectedIndex() != 2) {   // no presupuesto
                          float cant = Float.parseFloat(tabla.getValueAt(i, 3).toString());
                        //  if (cbTipoPago.getSelectedIndex()==2) cantidad = -cantidad; //resto el stock
                          Stock.menosStock(codigo, cant);
                       }
                    }                 
                    String datos2 [] = {tabla.getValueAt(i, 2).toString(), //detalle
                                     tabla.getValueAt(i, 5).toString().replace("%", ""), //margen
                                     tabla.getValueAt(i, 6).toString().replace("%", "").replace(",","."), //descuento
                                     tabla.getValueAt(i, 4).toString().replace(",","."), //precio
                                     tabla.getValueAt(i, 7).toString().replace(",","."), //total
                                     tabla.getValueAt(i, 3).toString(), //cantidad
                                     codigo,
                                     ""+cbTipoTicket.getSelectedIndex(),
                                     ""+tabla.getValueAt(i, 0), //pos
                                     ""+numTicket,
                                   };
                    FacturasAlbaranes.guardarLista(datos2);
                    guardarTicketCli(cbTipoTicket.getSelectedIndex());  
                }
                initNumTicket(numTicket);
                log.info("Guardar:  guardar->" + guardar + "  numTicket->" + numTicket + "  idimp->" + imp);
            }
            else {
                mostrarMensajeError(true, 3);
                return false;
            }
            guardar=true;
            abrirCajon();
            ConsultaBD.cursorNormal(this);
            if((cbTipoPago.getSelectedIndex()==0) && cbTipoPago.isVisible())
                mostrarMensajeError(true,5);    // nos dice cuanto tenemos que devolver
            return true;
        }
        else {
            mostrarMensajeError(true, 4);
            return false;
        }
    }
     
    public void cargar (String id, int albaran) {
        int idImp = Integer.parseInt(id.substring(5));
        String idF = id.substring(0, 4);
        cbTipoTicket.setSelectedIndex(albaran);
        txtIdImp.setValue(idImp);
        txtIdFecha.setText(idF);
        cargoDesdeOtraVentana = true;
        
        String sqlTabla = FacturasAlbaranes.getTablaSql(cbTipoTicket.getSelectedIndex());
        
        String sql = "select id from " +sqlTabla+ " where idImp = " + idImp + " and idAno = " + idF;
        ResultSet res = FacturasAlbaranes.getDatos(sql);
        try {
            if (res.next()) {
                numTicket = res.getInt("id");
                cargar();
            }
        } catch (SQLException ex) {
            numTicket = -1;  
            mostrarMensajeError(true, 0);
        }
    }
                    
    public void cargar () {
        ConsultaBD.cursorEspera(this);
        guardar = false;
        mostrarReloj(false);
        mostrarDatosCli(false);
        borrarTabla();
        totalVenta = 0;
        
        ResultSet datos = FacturasAlbaranes.getFacturaAlbaran(numTicket,cbTipoTicket.getSelectedIndex());
        try{
            //------------------------------------------------------------datos de Factura
            datos.next();
            cbTipoPago.setSelectedIndex(datos.getInt("tipopago"));
            getCliente(String.valueOf(datos.getInt("idcliente")));
     //       mostrarContado(cbTipoPago.getSelectedIndex() == 0 ? true: false);
            
            //descuento = datos.getFloat("descuento");
            txtDescuentoPie.setText(""+datos.getFloat("descuento") + "%");
            float totalFact = datos.getFloat("total");
            mostrarPrecioFinal(totalFact); 
            txtPrecioFinalMano.setText(String.valueOf(datos.getFloat("totalmano")));
            txtIdFecha.setText(""+datos.getInt("idAno"));
            txtIdImp.setValue(datos.getInt("idImp"));
            String fech [] = datos.getString("fecha").substring(0,11).trim().split("-");
            txtFecha.setText(fech[2] + "/" + fech[1] + "/" + fech[0]);
            fechaCrea = datos.getString("fechacrea").substring(0,11).trim();
            //fechaCrea = fechC[2] + "/" + fechC[1] + "/" + fechC[0];
            setPrecioFinal();
            txtComentario.setText(datos.getString("observacion"));
            cbVendedor.setSelectedIndex(datos.getInt("vendedor"));

            if((cbTipoTicket.getSelectedIndex()==0)||(cbTipoTicket.getSelectedIndex()==1)) {
                setPagoEn(datos.getInt("pagoEn"));
                entrego = datos.getFloat("entrego");
                txtEntrego.setText(""+entrego);
                txtNegro.setText(""+datos.getFloat("negro"));
            }
            //--------------------------------------------------------------Lista de articulos
            datos = FacturasAlbaranes.getListArticulos(numTicket, cbTipoTicket.getSelectedIndex());           
            while (datos.next()) {
                int codigo = datos.getInt("idarticulo");
                if (codigo == 0) // articulo puesto a mano
                   tabla.setValueAt(null, tabla.getRowCount()-1, 1);
                else {
                   tabla.setValueAt(codigo, tabla.getRowCount()-1, 1);
                   if (cbTipoTicket.getSelectedIndex() != 2) {   // presupuesto
                      float cant = -datos.getFloat("cantidad");
                      //if (cbTipoPago.getSelectedIndex()==2) cant = -cant; //resto el stock
                      Stock.menosStock(""+codigo, cant); // Restauro stock
                   }
                }
                tabla.setValueAt(datos.getString("detalle"), tabla.getRowCount()-1, 2);
                tabla.setValueAt(datos.getFloat("cantidad"), tabla.getRowCount()-1, 3);
                tabla.setValueAt(datos.getFloat("precio"), tabla.getRowCount()-1, 4);
                tabla.setValueAt(datos.getFloat("margen") + "%", tabla.getRowCount()-1, 5);
                tabla.setValueAt(datos.getFloat("descuento") + "%", tabla.getRowCount()-1, 6);
                total = datos.getFloat("total");
                totalVenta += total;
                tabla.setValueAt(total, tabla.getRowCount()-1, 7);  
                ((DefaultTableModel)tabla.getModel()).addRow(new Object[] {tabla.getRowCount()+1,null,null,null,null,null,null});
            }        
            tabla.scrollRectToVisible(tabla.getCellRect(tabla.getRowCount()-1, 0, true));
            //---------------------------------------------------------------
            if (totalFact <= Util.redondeo(totalVenta,2)) {
                mostrarPrecioFinal(totalVenta);
                setPrecioFinal();
            }
            
            mostrarMensajeError(false);
            cambiarEstadoTicket(false);
            habilitarIdTicket(false);
            txtBuscar.requestFocus();
            activarBotones(true);
        } catch (SQLException ex) {
                log.warn("cargar: " +ex);
                mostrarMensajeError(true);
                txtIdImp.requestFocus();
                txtIdImp.selectAll();
                habilitarIdTicket(true);
        }
        ConsultaBD.cursorNormal(this);
    }
    
    // funcion especifica que se encarga de cargar una factura de compra en una de venta
    public void convertir(ResultSet datos, int tipo, float marg) {
        try {
            ConsultaBD.cursorEspera(this);
            cbTipoTicket.setSelectedIndex(tipo);
            while (datos.next()) {
                int codigo = datos.getInt("idarticulo");
                if (codigo == 0) // articulo puesto a mano
                    tabla.setValueAt(null, tabla.getRowCount()-1, 1);
                else 
                    tabla.setValueAt(codigo, tabla.getRowCount()-1, 1);
                tabla.setValueAt(datos.getString("detalle"), tabla.getRowCount()-1, 2);
                
                cantidad = datos.getFloat("cantidad");
                precio = datos.getFloat("precio");
                margen = marg;
                descuento = datos.getFloat("descuento");
                
                calcular();
         
                tabla.setValueAt(cantidad, tabla.getRowCount()-1, 3);
                tabla.setValueAt(precio, tabla.getRowCount()-1, 4);
                tabla.setValueAt(margen + "%", tabla.getRowCount()-1, 5);
                tabla.setValueAt(descuento + "%", tabla.getRowCount()-1, 6);       
                tabla.setValueAt(total, tabla.getRowCount()-1, 7);  
                ((DefaultTableModel)tabla.getModel()).addRow(new Object[] {tabla.getRowCount()+1,null,null,null,null,null,null});
            }        
            guardar = true;
            tabla.scrollRectToVisible(tabla.getCellRect(tabla.getRowCount()-1, 0, true));
            cambiarEstadoTicket(false);
            txtBuscar.requestFocus();
            activarBotones(true);
        } catch (SQLException ex) {
            log.warn("convertir " + ex);
        }
        ConsultaBD.cursorNormal(this);
    }
    
    private void ColorVendedor() {
        Color c = null;
        switch (cbVendedor.getSelectedIndex()) {
            case 0:
                c = Color.red;
                break;
            case 1:
                c = Color.yellow;
                break;
            case 2:
                c = Color.blue;
                break;
            case 3:
                c = Color.green;
                break;
        }
        if (c != null) {
            this.setBackground(c);
            pBotones.setBackground(c);
            pCliente.setBackground(c);
            pDatosCliente.setBackground(c);
            pFecha.setBackground(c);
            pFinal.setBackground(c);
            pPago.setBackground(c);
            pPrecio.setBackground(c);
            //pProductos.setBackground(c);
            pReloj.setBackground(c);
            pTipoTicket.setBackground(c);
        }
    }
   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        grupo = new javax.swing.ButtonGroup();
        pDatosCliente = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        txtCliNombre = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtCliFiscal = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtCliDomicilio = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtCliLocalidad = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        txtCliCodPostal = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        txtCliTelefono = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        txtCliCIF = new javax.swing.JTextField();
        bListo = new javax.swing.JButton();
        pTipoTicket = new javax.swing.JPanel();
        cbTipoTicket = new javax.swing.JComboBox();
        txtCargarFactura = new javax.swing.JButton();
        cbTipoPago = new javax.swing.JComboBox();
        txtIdFecha = new javax.swing.JTextField();
        jLabel18 = new javax.swing.JLabel();
        txtIdImp = new javax.swing.JFormattedTextField();
        cbVendedor = new javax.swing.JComboBox();
        pCliente = new javax.swing.JPanel();
        txtCodCliente = new javax.swing.JTextField();
        txtNomComercial = new javax.swing.JTextField();
        lblError = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        pReloj = new javax.swing.JPanel();
        pFecha = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        txtFecha = new javax.swing.JTextField();
        lblTime = new javax.swing.JLabel();
        txtPrecioDigital = new javax.swing.JTextField();
        pProductos = new javax.swing.JPanel();
        txtBuscar = new javax.swing.JTextField();
        txtCantidad = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        lblQuitar = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        lblDesc = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        lblCant = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        lblMarg = new javax.swing.JTextField();
        jLabel19 = new javax.swing.JLabel();
        lblResetear = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        pPrecio = new javax.swing.JPanel();
        jLabel12 = new javax.swing.JLabel();
        txtDescuentoPie = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        txtPrecioFinal = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        txtPrecioFinalMano = new javax.swing.JTextField();
        lblDio = new javax.swing.JLabel();
        txtEntrego = new javax.swing.JTextField();
        chNoImpDescuento = new javax.swing.JCheckBox();
        pBotones = new javax.swing.JPanel();
        bTicket = new javax.swing.JButton();
        bImprimir = new javax.swing.JButton();
        bGuardar = new javax.swing.JButton();
        bBorrar = new javax.swing.JButton();
        bCajon = new javax.swing.JButton();
        txtNegro = new javax.swing.JTextField();
        pPago = new javax.swing.JPanel();
        rbEfectivo = new javax.swing.JRadioButton();
        rbTarjeta = new javax.swing.JRadioButton();
        rbCheque = new javax.swing.JRadioButton();
        rbTrans = new javax.swing.JRadioButton();
        rbVale = new javax.swing.JRadioButton();
        pFinal = new javax.swing.JPanel();
        jLabel17 = new javax.swing.JLabel();
        txtNumCopias = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        txtComentario = new javax.swing.JTextField();
        chNoOriginal = new javax.swing.JCheckBox();
        chPdf = new javax.swing.JCheckBox();

        setClosable(true);
        setTitle("TPV");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icono2.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosed(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        pDatosCliente.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        pDatosCliente.setMinimumSize(new java.awt.Dimension(370, 170));
        pDatosCliente.setPreferredSize(new java.awt.Dimension(370, 170));

        jLabel5.setText("Nombre");
        pDatosCliente.add(jLabel5);

        txtCliNombre.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCliNombre.setToolTipText("");
        txtCliNombre.setPreferredSize(new java.awt.Dimension(300, 20));
        pDatosCliente.add(txtCliNombre);

        jLabel6.setText("Fiscal");
        pDatosCliente.add(jLabel6);

        txtCliFiscal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCliFiscal.setPreferredSize(new java.awt.Dimension(300, 20));
        pDatosCliente.add(txtCliFiscal);

        jLabel7.setText("Domicilio");
        pDatosCliente.add(jLabel7);

        txtCliDomicilio.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCliDomicilio.setPreferredSize(new java.awt.Dimension(300, 20));
        pDatosCliente.add(txtCliDomicilio);

        jLabel8.setText("Localidad");
        pDatosCliente.add(jLabel8);

        txtCliLocalidad.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCliLocalidad.setPreferredSize(new java.awt.Dimension(100, 20));
        pDatosCliente.add(txtCliLocalidad);

        jLabel9.setText("Cod.Postal");
        pDatosCliente.add(jLabel9);

        txtCliCodPostal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCliCodPostal.setPreferredSize(new java.awt.Dimension(100, 20));
        pDatosCliente.add(txtCliCodPostal);

        jLabel10.setText("Telefono");
        pDatosCliente.add(jLabel10);

        txtCliTelefono.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCliTelefono.setPreferredSize(new java.awt.Dimension(100, 20));
        pDatosCliente.add(txtCliTelefono);

        jLabel11.setText("CIF / DNI");
        pDatosCliente.add(jLabel11);

        txtCliCIF.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCliCIF.setToolTipText("");
        txtCliCIF.setPreferredSize(new java.awt.Dimension(100, 20));
        pDatosCliente.add(txtCliCIF);

        bListo.setText("Listo");
        bListo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bListoActionPerformed(evt);
            }
        });
        pDatosCliente.add(bListo);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.insets = new java.awt.Insets(40, 30, 0, 0);
        getContentPane().add(pDatosCliente, gridBagConstraints);

        pTipoTicket.setMinimumSize(new java.awt.Dimension(385, 40));
        pTipoTicket.setPreferredSize(new java.awt.Dimension(385, 40));
        pTipoTicket.setLayout(new java.awt.GridBagLayout());

        cbTipoTicket.setMaximumRowCount(4);
        cbTipoTicket.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Factura", "Albaran", "Presupuesto", "Fiado" }));
        cbTipoTicket.setMinimumSize(new java.awt.Dimension(100, 20));
        cbTipoTicket.setPreferredSize(new java.awt.Dimension(100, 20));
        cbTipoTicket.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTipoTicketItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pTipoTicket.add(cbTipoTicket, gridBagConstraints);

        txtCargarFactura.setText("Cargar");
        txtCargarFactura.setPreferredSize(new java.awt.Dimension(65, 28));
        txtCargarFactura.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCargarFacturaActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
        pTipoTicket.add(txtCargarFactura, gridBagConstraints);

        cbTipoPago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Contado", "Credito", "Vale" }));
        cbTipoPago.setMinimumSize(new java.awt.Dimension(82, 20));
        cbTipoPago.setPreferredSize(new java.awt.Dimension(82, 20));
        cbTipoPago.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTipoPagoItemStateChanged(evt);
            }
        });
        cbTipoPago.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                cbTipoPagoFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                cbTipoPagoFocusLost(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        pTipoTicket.add(cbTipoPago, gridBagConstraints);

        txtIdFecha.setEditable(false);
        txtIdFecha.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtIdFecha.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtIdFecha.setText("2014");
        txtIdFecha.setToolTipText("yyyy");
        txtIdFecha.setMinimumSize(new java.awt.Dimension(55, 28));
        txtIdFecha.setPreferredSize(new java.awt.Dimension(55, 28));
        txtIdFecha.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtIdFechaMouseClicked(evt);
            }
        });
        txtIdFecha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtIdFechaKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        pTipoTicket.add(txtIdFecha, gridBagConstraints);

        jLabel18.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel18.setText("-");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        pTipoTicket.add(jLabel18, gridBagConstraints);

        txtIdImp.setEditable(false);
        txtIdImp.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("000000"))));
        txtIdImp.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtIdImp.setText("654321");
        txtIdImp.setToolTipText("f2: asignar un nuevo id al ticket");
        txtIdImp.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtIdImp.setMinimumSize(new java.awt.Dimension(80, 28));
        txtIdImp.setPreferredSize(new java.awt.Dimension(80, 28));
        txtIdImp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtIdImpMouseClicked(evt);
            }
        });
        txtIdImp.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtIdImpKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        pTipoTicket.add(txtIdImp, gridBagConstraints);

        cbVendedor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ale", "Onan", "Tino", "Juan" }));
        cbVendedor.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbVendedorItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 1);
        pTipoTicket.add(cbVendedor, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(15, 20, 3, 0);
        getContentPane().add(pTipoTicket, gridBagConstraints);

        pCliente.setMinimumSize(new java.awt.Dimension(380, 40));
        pCliente.setPreferredSize(new java.awt.Dimension(380, 40));
        pCliente.setLayout(new java.awt.GridBagLayout());

        txtCodCliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtCodCliente.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCodCliente.setText("0");
        txtCodCliente.setToolTipText("f2: busqueda de clientes");
        txtCodCliente.setMinimumSize(new java.awt.Dimension(35, 30));
        txtCodCliente.setPreferredSize(new java.awt.Dimension(35, 30));
        txtCodCliente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtCodClienteMouseClicked(evt);
            }
        });
        txtCodCliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodClienteKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
        pCliente.add(txtCodCliente, gridBagConstraints);

        txtNomComercial.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtNomComercial.setText("Ventas Contado");
        txtNomComercial.setToolTipText("f2: apertura de campos cliente");
        txtNomComercial.setMinimumSize(new java.awt.Dimension(35, 30));
        txtNomComercial.setPreferredSize(new java.awt.Dimension(59, 30));
        txtNomComercial.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNomComercialKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 300;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        pCliente.add(txtNomComercial, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 0);
        getContentPane().add(pCliente, gridBagConstraints);

        lblError.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        lblError.setForeground(new java.awt.Color(255, 0, 0));
        lblError.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblError.setText("<html><p align=center> ¡¡¡¡Error!!!!<br> Ticket no Existe</p>");
        lblError.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        lblError.setMinimumSize(new java.awt.Dimension(300, 100));
        lblError.setOpaque(true);
        lblError.setPreferredSize(new java.awt.Dimension(300, 100));
        lblError.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblErrorMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 3;
        getContentPane().add(lblError, gridBagConstraints);

        jScrollPane1.setMinimumSize(new java.awt.Dimension(300, 150));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(300, 150));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null}
            },
            new String [] {
                "nº", "Codigo", "Detalle", "Cantidad", "Precio", "Margen", "Descuento", "Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Float.class, java.lang.Float.class, java.lang.String.class, java.lang.String.class, java.lang.Float.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, true, true, true, true, true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabla.setToolTipText("<html> boton dcho: abre el articulo<br> f1: borra linea");
        tabla.getTableHeader().setReorderingAllowed(false);
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        tabla.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tablaKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tablaKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);
        if (tabla.getColumnModel().getColumnCount() > 0) {
            tabla.getColumnModel().getColumn(0).setResizable(false);
            tabla.getColumnModel().getColumn(0).setPreferredWidth(30);
            tabla.getColumnModel().getColumn(1).setResizable(false);
            tabla.getColumnModel().getColumn(2).setResizable(false);
            tabla.getColumnModel().getColumn(2).setPreferredWidth(300);
            tabla.getColumnModel().getColumn(3).setResizable(false);
            tabla.getColumnModel().getColumn(4).setResizable(false);
            tabla.getColumnModel().getColumn(5).setResizable(false);
            tabla.getColumnModel().getColumn(6).setResizable(false);
            tabla.getColumnModel().getColumn(7).setResizable(false);
        }

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 5, 10);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        pReloj.setPreferredSize(new java.awt.Dimension(300, 158));
        pReloj.setLayout(new java.awt.GridBagLayout());

        pFecha.setMinimumSize(new java.awt.Dimension(100, 30));
        pFecha.setPreferredSize(new java.awt.Dimension(100, 30));
        pFecha.setLayout(new java.awt.GridBagLayout());

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel4.setText("Fecha de la Venta");
        jLabel4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel4MouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
        pFecha.add(jLabel4, gridBagConstraints);

        txtFecha.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtFecha.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFecha.setToolTipText("dd/mm/yyyy");
        txtFecha.setMinimumSize(new java.awt.Dimension(110, 30));
        txtFecha.setPreferredSize(new java.awt.Dimension(110, 30));
        txtFecha.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtFechaMouseClicked(evt);
            }
        });
        txtFecha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtFechaKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pFecha.add(txtFecha, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pReloj.add(pFecha, gridBagConstraints);

        lblTime.setBackground(new java.awt.Color(0, 0, 0));
        lblTime.setFont(new java.awt.Font("Raavi", 0, 18)); // NOI18N
        lblTime.setForeground(new java.awt.Color(255, 255, 255));
        lblTime.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTime.setText("19/11/2013   09:38:00");
        lblTime.setAlignmentY(0.0F);
        lblTime.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, null, new java.awt.Color(153, 153, 153), null, new java.awt.Color(51, 51, 51)));
        lblTime.setMaximumSize(new java.awt.Dimension(300, 37));
        lblTime.setMinimumSize(new java.awt.Dimension(300, 30));
        lblTime.setOpaque(true);
        lblTime.setPreferredSize(new java.awt.Dimension(100, 30));
        lblTime.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblTimeMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pReloj.add(lblTime, gridBagConstraints);

        txtPrecioDigital.setEditable(false);
        txtPrecioDigital.setBackground(new java.awt.Color(255, 255, 255));
        txtPrecioDigital.setFont(new java.awt.Font("MS UI Gothic", 1, 40)); // NOI18N
        txtPrecioDigital.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtPrecioDigital.setText("0,00€");
        txtPrecioDigital.setFocusable(false);
        txtPrecioDigital.setMaximumSize(new java.awt.Dimension(300, 60));
        txtPrecioDigital.setMinimumSize(new java.awt.Dimension(300, 60));
        txtPrecioDigital.setPreferredSize(new java.awt.Dimension(300, 60));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipady = 40;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        pReloj.add(txtPrecioDigital, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(10, 415, 0, 20);
        getContentPane().add(pReloj, gridBagConstraints);

        pProductos.setMaximumSize(new java.awt.Dimension(380, 71));
        pProductos.setMinimumSize(new java.awt.Dimension(380, 69));
        pProductos.setPreferredSize(new java.awt.Dimension(380, 71));
        pProductos.setLayout(new java.awt.GridBagLayout());

        txtBuscar.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtBuscar.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtBuscar.setToolTipText("f2: busqueda de articulo");
        txtBuscar.setMinimumSize(new java.awt.Dimension(200, 30));
        txtBuscar.setPreferredSize(new java.awt.Dimension(200, 30));
        txtBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtBuscarMouseClicked(evt);
            }
        });
        txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(6, 5, 5, 0);
        pProductos.add(txtBuscar, gridBagConstraints);

        txtCantidad.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        txtCantidad.setText("1,0x");
        txtCantidad.setToolTipText("");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 0);
        pProductos.add(txtCantidad, gridBagConstraints);

        jPanel3.setMinimumSize(new java.awt.Dimension(350, 30));
        jPanel3.setPreferredSize(new java.awt.Dimension(350, 30));

        lblQuitar.setEditable(false);
        lblQuitar.setBackground(new java.awt.Color(255, 255, 51));
        lblQuitar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblQuitar.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        lblQuitar.setText("-");
        lblQuitar.setPreferredSize(new java.awt.Dimension(20, 20));
        jPanel3.add(lblQuitar);

        jLabel3.setText("Quitar");
        jPanel3.add(jLabel3);

        lblDesc.setEditable(false);
        lblDesc.setBackground(new java.awt.Color(255, 255, 51));
        lblDesc.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblDesc.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        lblDesc.setText("/");
        lblDesc.setPreferredSize(new java.awt.Dimension(20, 20));
        jPanel3.add(lblDesc);

        jLabel2.setText("Descuentos");
        jPanel3.add(jLabel2);

        lblCant.setEditable(false);
        lblCant.setBackground(new java.awt.Color(255, 255, 51));
        lblCant.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblCant.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        lblCant.setText("*");
        lblCant.setPreferredSize(new java.awt.Dimension(20, 20));
        jPanel3.add(lblCant);

        jLabel1.setText("Cantidad");
        jPanel3.add(jLabel1);

        lblMarg.setEditable(false);
        lblMarg.setBackground(new java.awt.Color(255, 255, 51));
        lblMarg.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblMarg.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        lblMarg.setText("+");
        lblMarg.setPreferredSize(new java.awt.Dimension(20, 20));
        jPanel3.add(lblMarg);

        jLabel19.setText("Margen");
        jPanel3.add(jLabel19);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 6;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        pProductos.add(jPanel3, gridBagConstraints);

        lblResetear.setEditable(false);
        lblResetear.setBackground(new java.awt.Color(255, 255, 51));
        lblResetear.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblResetear.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        lblResetear.setText("sup");
        lblResetear.setMinimumSize(new java.awt.Dimension(40, 20));
        lblResetear.setPreferredSize(new java.awt.Dimension(40, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
        pProductos.add(lblResetear, gridBagConstraints);

        jLabel15.setText("Borrar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        pProductos.add(jLabel15, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 0);
        getContentPane().add(pProductos, gridBagConstraints);

        pPrecio.setMinimumSize(new java.awt.Dimension(210, 150));
        pPrecio.setOpaque(false);
        pPrecio.setPreferredSize(new java.awt.Dimension(210, 150));
        pPrecio.setLayout(new java.awt.GridBagLayout());

        jLabel12.setText("Descuento");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        pPrecio.add(jLabel12, gridBagConstraints);

        txtDescuentoPie.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtDescuentoPie.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtDescuentoPie.setText("0%");
        txtDescuentoPie.setMinimumSize(new java.awt.Dimension(100, 30));
        txtDescuentoPie.setName("txtDescuentoPie"); // NOI18N
        txtDescuentoPie.setPreferredSize(new java.awt.Dimension(100, 30));
        txtDescuentoPie.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtDescuentoPieMouseClicked(evt);
            }
        });
        txtDescuentoPie.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtDescuentoPieKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pPrecio.add(txtDescuentoPie, gridBagConstraints);

        jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel13.setText("Precio");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        pPrecio.add(jLabel13, gridBagConstraints);

        txtPrecioFinal.setEditable(false);
        txtPrecioFinal.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtPrecioFinal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtPrecioFinal.setText("0,00€");
        txtPrecioFinal.setBorder(null);
        txtPrecioFinal.setMinimumSize(new java.awt.Dimension(100, 30));
        txtPrecioFinal.setPreferredSize(new java.awt.Dimension(100, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pPrecio.add(txtPrecioFinal, gridBagConstraints);

        jLabel14.setText("Precio Final a mano");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        pPrecio.add(jLabel14, gridBagConstraints);

        txtPrecioFinalMano.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtPrecioFinalMano.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtPrecioFinalMano.setToolTipText("Cualquier letra final a 0");
        txtPrecioFinalMano.setMinimumSize(new java.awt.Dimension(100, 30));
        txtPrecioFinalMano.setName("txtPrecioFinalMano"); // NOI18N
        txtPrecioFinalMano.setPreferredSize(new java.awt.Dimension(100, 30));
        txtPrecioFinalMano.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPrecioFinalManoMouseClicked(evt);
            }
        });
        txtPrecioFinalMano.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPrecioFinalManoFocusLost(evt);
            }
        });
        txtPrecioFinalMano.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPrecioFinalManoKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pPrecio.add(txtPrecioFinalMano, gridBagConstraints);

        lblDio.setText("Entregado");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        pPrecio.add(lblDio, gridBagConstraints);

        txtEntrego.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtEntrego.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtEntrego.setToolTipText("");
        txtEntrego.setMinimumSize(new java.awt.Dimension(100, 30));
        txtEntrego.setName("txtEntrego"); // NOI18N
        txtEntrego.setPreferredSize(new java.awt.Dimension(100, 30));
        txtEntrego.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtEntregoMouseClicked(evt);
            }
        });
        txtEntrego.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtEntregoFocusLost(evt);
            }
        });
        txtEntrego.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtEntregoKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pPrecio.add(txtEntrego, gridBagConstraints);

        chNoImpDescuento.setText("No imprimir descuento");
        chNoImpDescuento.setName("chNoImpDescuento"); // NOI18N
        chNoImpDescuento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                chNoImpDescuentoKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 2;
        pPrecio.add(chNoImpDescuento, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 15, 10);
        getContentPane().add(pPrecio, gridBagConstraints);

        pBotones.setMinimumSize(new java.awt.Dimension(350, 80));
        pBotones.setPreferredSize(new java.awt.Dimension(350, 80));
        pBotones.setLayout(new java.awt.GridBagLayout());

        bTicket.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/TICKET3.png"))); // NOI18N
        bTicket.setToolTipText("Ticket ");
        bTicket.setMaximumSize(new java.awt.Dimension(60, 60));
        bTicket.setMinimumSize(new java.awt.Dimension(60, 60));
        bTicket.setName("bTicket"); // NOI18N
        bTicket.setPreferredSize(new java.awt.Dimension(70, 70));
        bTicket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bTicketActionPerformed(evt);
            }
        });
        bTicket.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                bTicketKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        pBotones.add(bTicket, gridBagConstraints);

        bImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/imprimir.png"))); // NOI18N
        bImprimir.setToolTipText("Imprimir");
        bImprimir.setMaximumSize(new java.awt.Dimension(60, 60));
        bImprimir.setMinimumSize(new java.awt.Dimension(60, 60));
        bImprimir.setName("bImprimir"); // NOI18N
        bImprimir.setPreferredSize(new java.awt.Dimension(70, 70));
        bImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bImprimirActionPerformed(evt);
            }
        });
        bImprimir.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                bImprimirKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        pBotones.add(bImprimir, gridBagConstraints);

        bGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/guardar.png"))); // NOI18N
        bGuardar.setToolTipText("Guardar");
        bGuardar.setMaximumSize(new java.awt.Dimension(60, 60));
        bGuardar.setMinimumSize(new java.awt.Dimension(60, 60));
        bGuardar.setName("bGuardar"); // NOI18N
        bGuardar.setPreferredSize(new java.awt.Dimension(70, 70));
        bGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bGuardarActionPerformed(evt);
            }
        });
        bGuardar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                bGuardarKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        pBotones.add(bGuardar, gridBagConstraints);

        bBorrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        bBorrar.setToolTipText("Reset");
        bBorrar.setMaximumSize(new java.awt.Dimension(60, 60));
        bBorrar.setMinimumSize(new java.awt.Dimension(60, 60));
        bBorrar.setName("bBorrar"); // NOI18N
        bBorrar.setPreferredSize(new java.awt.Dimension(70, 70));
        bBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bBorrarActionPerformed(evt);
            }
        });
        bBorrar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                bBorrarKeyReleased(evt);
            }
        });
        pBotones.add(bBorrar, new java.awt.GridBagConstraints());

        bCajon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cajon.png"))); // NOI18N
        bCajon.setToolTipText("Abrir Cajon (F4)");
        bCajon.setPreferredSize(new java.awt.Dimension(50, 50));
        bCajon.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        bCajon.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bCajonMouseClicked(evt);
            }
        });
        bCajon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCajonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
        pBotones.add(bCajon, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 50);
        getContentPane().add(pBotones, gridBagConstraints);

        txtNegro.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtNegro.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtNegro.setMinimumSize(new java.awt.Dimension(70, 28));
        txtNegro.setName("txtNegro"); // NOI18N
        txtNegro.setPreferredSize(new java.awt.Dimension(70, 28));
        txtNegro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNegroKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 30, 130);
        getContentPane().add(txtNegro, gridBagConstraints);

        pPago.setMinimumSize(new java.awt.Dimension(100, 110));
        pPago.setPreferredSize(new java.awt.Dimension(100, 110));
        pPago.setLayout(new java.awt.GridBagLayout());

        rbEfectivo.setText("Efectivo");
        rbEfectivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbEfectivoActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pPago.add(rbEfectivo, gridBagConstraints);

        rbTarjeta.setText("Tarjeta");
        rbTarjeta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbTarjetaActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pPago.add(rbTarjeta, gridBagConstraints);

        rbCheque.setText("Cheque");
        rbCheque.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbChequeActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pPago.add(rbCheque, gridBagConstraints);

        rbTrans.setText("Transferencia");
        rbTrans.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbTransActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pPago.add(rbTrans, gridBagConstraints);

        rbVale.setText("Vale");
        rbVale.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbValeActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pPago.add(rbVale, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 370, 0, 0);
        getContentPane().add(pPago, gridBagConstraints);

        pFinal.setMinimumSize(new java.awt.Dimension(530, 50));
        pFinal.setPreferredSize(new java.awt.Dimension(530, 50));
        pFinal.setLayout(new java.awt.GridBagLayout());

        jLabel17.setText("Num Copias");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        pFinal.add(jLabel17, gridBagConstraints);

        txtNumCopias.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtNumCopias.setText("0");
        txtNumCopias.setMinimumSize(new java.awt.Dimension(20, 20));
        txtNumCopias.setPreferredSize(new java.awt.Dimension(20, 20));
        txtNumCopias.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtNumCopiasMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
        pFinal.add(txtNumCopias, gridBagConstraints);

        jLabel16.setText("Comentario");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
        pFinal.add(jLabel16, gridBagConstraints);

        txtComentario.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtComentario.setMinimumSize(new java.awt.Dimension(420, 20));
        txtComentario.setPreferredSize(new java.awt.Dimension(420, 20));
        txtComentario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtComentarioMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 6;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pFinal.add(txtComentario, gridBagConstraints);

        chNoOriginal.setText("No sacar original");
        chNoOriginal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chNoOriginalActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 20);
        pFinal.add(chNoOriginal, gridBagConstraints);

        chPdf.setText("Imp. PDF");
        chPdf.setName("chPdf"); // NOI18N
        chPdf.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                chPdfKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
        pFinal.add(chPdf, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
        getContentPane().add(pFinal, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents
     
    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
        int fila = tabla.rowAtPoint(evt.getPoint());
        int colum = tabla.columnAtPoint(evt.getPoint());
        if ((fila > -1) && (colum > -1)) {
            setVarFila(fila);
            filaEdit = fila;
            columEdit = colum;
            if (colum == 3) pasada = 1;
        }
    }//GEN-LAST:event_tablaMouseClicked

    // tratamiento del campo buscar
    private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased
        switch (evt.getKeyCode()) {
            case 10: 
                if (txtBuscar.getText().isEmpty()) {
                    txtEntrego.requestFocus();
                }
                else
                    añadirArticulo();
                break;
            case 106:   // tecla *
                cantidad = Float.parseFloat(txtBuscar.getText().replace("*", "").trim());
                txtCantidad.setText(Float.toString(cantidad).replace(".", ",") + "x");
                txtCantidad.setForeground(Color.black);
                txtBuscar.setText("");
                break;
            case 109:   // tecla -
                cantidad = -Float.parseFloat(txtBuscar.getText().replace("-", "").trim());
                txtCantidad.setText(Float.toString(cantidad).replace(".", ",") + "x");
                txtCantidad.setForeground(Color.red);
                txtBuscar.setText("");
                break;
            case 111:   // tecla /
                descuento = Float.parseFloat(txtBuscar.getText().replace("/", "").trim());
                txtBuscar.setText("");
                break;
            case 107:   // tecla +
                margen = Float.parseFloat(txtBuscar.getText().replace("+", "").trim());
                txtBuscar.setText("");
                break;
            case 113:   //f2
                abrirBusquedaArticulo(null);
                break;
            case 127:    // sup
                resetValores();
                margen = 0;
                break;
            default:
                buscar = true;
                break;
        }    
    }//GEN-LAST:event_txtBuscarKeyReleased

    // Borra la fila selecionada
    private void tablaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaKeyReleased
        int fila = tabla.getSelectedRow();
        int columna = tabla.getSelectedColumn();
       
        switch (evt.getKeyCode()) { 
            case 37:
            case 38:
            case 39:
            case 40:
                if (fila != filaEdit) {
                    setVarFila(fila);
                    filaEdit = fila;
                }
                columEdit = columna;
                tabla.editCellAt(fila, columna);
                tabla.changeSelection(fila, columna, false, false);
                if (columna == 3) pasada = 1;
                break;
            case 112:    //f1
            case 46:     //supr
                if (fila > -1) {
                    tabla.getCellEditor().cancelCellEditing();
                    if (tabla.getRowCount() > 1) {
                        txtBuscar.requestFocus();
                        setVarFila(fila);
                        cantidad = -cantidad;
                        calcular();
                        resetValores();
                        ((DefaultTableModel)tabla.getModel()).removeRow(fila);
                        for(int i = fila ; i < tabla.getRowCount(); i++)
                            tabla.setValueAt(i+1, i, 0);
                        if(tabla.getRowCount()<=17)bTicket.setEnabled(true);
                    }
                    pasada = 1;
                }
                break;
            case 10: 
                tabla.editCellAt(filaEdit, columEdit+1);
                tabla.changeSelection(filaEdit, columEdit+1, false, false);
                switch (columEdit) {
                    case 2: pasada = 1;
                        break;
                    case 3:
                        if ((tabla.getValueAt(filaEdit, 1) != null) && !tabla.getValueAt(filaEdit, 1).toString().isEmpty()
                            && (pasada == 1)) {
                            verStock(tabla.getValueAt(filaEdit, 1).toString(), Float.parseFloat(""+tabla.getValueAt(filaEdit, 3)) );
                            pasada = 2;
                    }
                        break;
                }
                break;
        }
    }//GEN-LAST:event_tablaKeyReleased

    private void cbTipoTicketItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTipoTicketItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            if (!guardar)
                resetFTPV();
            else
                initNumTicket(0);
            
            cbTipoPago.setVisible(true);
            mostrarContado(true);
            switch (cbTipoTicket.getSelectedIndex()){
                case 0:         // facturas
                    cbTipoPago.setSelectedIndex(0);
                    txtNegro.setVisible(false);
                    break;
                case 1:         // albaranes
                    cbTipoPago.setSelectedIndex(1);
                    break;
                case 2:         // presupuestos
                case 3:         // fiados
                    cbTipoPago.setVisible(false);
                    cbTipoPago.setSelectedIndex(0);
                    mostrarContado(false);
                    break;
                    
            }    
            setNumCopias();
        }
    }//GEN-LAST:event_cbTipoTicketItemStateChanged

    private void txtCodClienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodClienteKeyPressed
        switch (evt.getKeyCode()) {
        case 113:       //f2
            log.debug("Pulse f2");
            FClientes c = new FClientes(this,"tpv");
            this.getParent().add(c);
            Principal.centrarFrame(c);
            c.show();
            break;
        case 10:        // Enter 
            getCliente(txtCodCliente.getText());    
            break;
        }            
    }//GEN-LAST:event_txtCodClienteKeyPressed

    private void txtNomComercialKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNomComercialKeyPressed
        if (evt.getKeyCode() == 113) { //f2
            mostrarDatosCli(true);
            
        }
    }//GEN-LAST:event_txtNomComercialKeyPressed

    private void bListoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bListoActionPerformed
        if (!txtCliNombre.getText().equals(""))
            txtNomComercial.setText(txtCliNombre.getText()); 
        mostrarDatosCli(false);
    }//GEN-LAST:event_bListoActionPerformed

    private void tablaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaKeyPressed
        if (evt.getKeyCode() == 10) {
            filaEdit = tabla.getSelectedRow();
            columEdit = tabla.getSelectedColumn();
            log.debug("Edite(" +filaEdit + ", " + columEdit+")");
        }
    }//GEN-LAST:event_tablaKeyPressed

    private void txtPrecioFinalManoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPrecioFinalManoKeyReleased
        if (evt.getKeyCode() == 10) {
           setPrecioFinal();
           txtEntrego.requestFocus();
        }
        else
            movermePrecios(evt);
    }//GEN-LAST:event_txtPrecioFinalManoKeyReleased

    private void txtDescuentoPieMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtDescuentoPieMouseClicked
        txtDescuentoPie.selectAll();
    }//GEN-LAST:event_txtDescuentoPieMouseClicked

    private void txtPrecioFinalManoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtPrecioFinalManoMouseClicked
        txtPrecioFinalMano.selectAll();
    }//GEN-LAST:event_txtPrecioFinalManoMouseClicked

    private void txtDescuentoPieKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescuentoPieKeyReleased
        if (evt.getKeyCode() == 10) {
           descuentoPie();
           txtEntrego.requestFocus();
        }
        else
            movermePrecios(evt);
    }//GEN-LAST:event_txtDescuentoPieKeyReleased

    private void bGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGuardarActionPerformed
        if (guardar())
            if (!cargoDesdeOtraVentana)
                resetFTPV();
            else 
                this.dispose();
        
    }//GEN-LAST:event_bGuardarActionPerformed

    private void txtCargarFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCargarFacturaActionPerformed
        boolean valor = !txtIdImp.isEditable();
        habilitarIdTicket(valor);   
        cambiarEstadoTicket(valor);
        if (valor) {
            txtIdImp.requestFocus();
            txtIdImp.selectAll();
        }
    }//GEN-LAST:event_txtCargarFacturaActionPerformed

    private void txtCodClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtCodClienteMouseClicked
        txtCodCliente.selectAll();
    }//GEN-LAST:event_txtCodClienteMouseClicked

    private void bBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBorrarActionPerformed
        // al cargar restauro el stock que habia en factura con lo si cancelo tengo que volver a guardarlo
        if (!guardar && (cbTipoTicket.getSelectedIndex() != 2)) {
            Util.restaurarStock(numTicket, cbTipoTicket.getSelectedIndex(), false);
            guardar = true;
        }
        if (!cargoDesdeOtraVentana) {
            resetFTPV();
            mostrarMensajeError(false);
        } else
            this.dispose();
    }//GEN-LAST:event_bBorrarActionPerformed

    private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed
        if (!guardar && (cbTipoTicket.getSelectedIndex() != 2)) {
            Util.restaurarStock(numTicket, cbTipoTicket.getSelectedIndex(), false);
        }
        ConsultaBD.cursorNormal(this);
    }//GEN-LAST:event_formInternalFrameClosed

    private void bImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bImprimirActionPerformed
        if (guardar()) {
            int imp = chPdf.isSelected()? 2:0;
            ImpVenta.imprime(imp, getDatosToImprimir());
            if (!cargoDesdeOtraVentana)
                resetFTPV();
            else
                this.dispose();
        }
    }//GEN-LAST:event_bImprimirActionPerformed

    private void txtNumCopiasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtNumCopiasMouseClicked
        txtNumCopias.selectAll();
    }//GEN-LAST:event_txtNumCopiasMouseClicked

    private void txtComentarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtComentarioMouseClicked
        txtComentario.selectAll();
    }//GEN-LAST:event_txtComentarioMouseClicked

    private void bTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bTicketActionPerformed
        if(guardar()) {
            boolean imprime = true;
            if (tabla.getRowCount() > 17) 
                 if (1==JOptionPane.showOptionDialog(this,  "¿Continuar impresion?",
                                                            "El numero de articulos excede el tamaño del ticket",  
                                                            JOptionPane.YES_NO_OPTION,                    
                                                            JOptionPane.QUESTION_MESSAGE,
                                                            null,    // null para icono por defecto.
                                                            new Object[] { "Continuar", "Cancelar"},   // null para YES, NO y CANCEL
                                                            "Continuar")) {
                     imprime = false;
                 }
             if (imprime){    
                if (cbTipoPago.getSelectedIndex() != 2)
                    ImpVenta.imprime(1, getDatosToImprimir());
                else {  // vale
                    DatosToImprimir d = new DatosToImprimir();
                    d.setTipoTicket(cbTipoTicket.getSelectedItem().toString());
                    d.setNumTicket(txtIdFecha.getText()+ "-" + txtIdImp.getText()); 
                    d.setFecha(new Fecha().getFecha());
                    //d.setPrecioMano(""+(-Float.parseFloat(txtPrecioDigital.getText().replace(",",".").replace("€", ""))));
                    d.setPrecioMano(""+(-Float.parseFloat(txtPrecioDigital.getText().replace(",",".").replace("€", ""))));
                    ImpVale.imprime(d);
                }
             }

            if (!cargoDesdeOtraVentana)
                resetFTPV();
            else
                this.dispose();
        }
    }//GEN-LAST:event_bTicketActionPerformed

    private void txtFechaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaMouseClicked
        txtFecha.selectAll();
        mostrarReloj(false);
    }//GEN-LAST:event_txtFechaMouseClicked

    private void txtFechaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFechaKeyReleased
        if (evt.getKeyCode() == 10) {
            if (Fecha.formatoCorrecto(txtFecha.getText())) {
                if (guardar)
                    mostrarReloj(true);
                mostrarMensajeError(false);
            } else 
                mostrarMensajeError(true, 2);
        } 
    }//GEN-LAST:event_txtFechaKeyReleased

    private void lblTimeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblTimeMouseClicked
        mostrarReloj(false);
    }//GEN-LAST:event_lblTimeMouseClicked

    private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel4MouseClicked
        mostrarReloj(true);
    }//GEN-LAST:event_jLabel4MouseClicked

    private void cbTipoPagoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTipoPagoItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            switch(cbTipoPago.getSelectedIndex()) {
               case 0:
                  txtNumCopias.setText("0");
                  if(!guardar && cambioEstado) {
                     txtNumCopias.setText("0");
                     int seleccion = JOptionPane.showOptionDialog(this, "Seleccione opcion", "¿Que fecha quiere para la factura?", 
                                                            JOptionPane.YES_NO_CANCEL_OPTION,                    
                                                            JOptionPane.QUESTION_MESSAGE,
                                                            null,    // null para icono por defecto.
                                                            new Object[] { "Hoy", "Vieja", "Otra"},   // null para YES, NO y CANCEL
                                                            "Hoy");
                     if (seleccion != -1) {
                        switch (seleccion) {
                            case 0:
                                txtFecha.setText(new Fecha().getFecha().replaceAll("-", "/"));
                                break;
                            case 1:
                                break;
                            case 2:
                                txtFecha.requestFocus();
                                txtFecha.selectAll();
                                break;
                        }
                    }
                  }
                
                  mostrarContado(cbTipoPago.isVisible());
                  break;
               case 1:
                   comprobarCredito(Clientes.getCredito(txtCodCliente.getText()));
                   mostrarContado(false);
                   break;
               case 2:
                   mostrarContado(true);
                   break;
            }
        }
    }//GEN-LAST:event_cbTipoPagoItemStateChanged

    private void lblErrorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblErrorMouseClicked
        mostrarMensajeError(false);
    }//GEN-LAST:event_lblErrorMouseClicked

    private void txtIdFechaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtIdFechaMouseClicked
        if(txtIdFecha.isEditable())
            txtIdFecha.selectAll();
    }//GEN-LAST:event_txtIdFechaMouseClicked

    private void txtIdImpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtIdImpMouseClicked
        if (txtIdImp.isEditable())
            txtIdImp.selectAll();
    }//GEN-LAST:event_txtIdImpMouseClicked

    private void txtIdImpKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtIdImpKeyReleased
        switch(evt.getKeyCode()) {
            case 10:    //enter
                numTicket = FacturasAlbaranes.getIdFacturaAlbaran(txtIdImp.getText(), txtIdFecha.getText(), cbTipoTicket.getSelectedIndex());
                cargar();
                break;
            case 113:   //f2
                //log.warn("le di a f2");
                numIdImp = JOptionPane.showInputDialog(this, "Numero de factura");
                txtIdImp.setText(numIdImp);
                break;
        }
    }//GEN-LAST:event_txtIdImpKeyReleased

    private void txtIdFechaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtIdFechaKeyReleased
        if (evt.getKeyCode() == 10) {
            initNumTicket(0);
            habilitarIdTicket(true);   
            cambiarEstadoTicket(true);
            txtIdImp.requestFocus();
        } 
    }//GEN-LAST:event_txtIdFechaKeyReleased

    private void txtBuscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtBuscarMouseClicked
        txtBuscar.selectAll();
    }//GEN-LAST:event_txtBuscarMouseClicked

    private void cbTipoPagoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cbTipoPagoFocusLost
        cambioEstado = false;
    }//GEN-LAST:event_cbTipoPagoFocusLost

    private void cbTipoPagoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cbTipoPagoFocusGained
        cambioEstado = true;
    }//GEN-LAST:event_cbTipoPagoFocusGained

    private void bCajonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCajonActionPerformed
        ImpVenta.abrirCajon();
    }//GEN-LAST:event_bCajonActionPerformed

    private void chNoOriginalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chNoOriginalActionPerformed
        txtNumCopias.setText("0");
    }//GEN-LAST:event_chNoOriginalActionPerformed

    private void resetNegro() {
        txtNegro.setVisible(false);
        if(guardar)
            txtNegro.setText("0");
    }
    
    private void rbTarjetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbTarjetaActionPerformed
        resetNegro();
        setEntrego();
    }//GEN-LAST:event_rbTarjetaActionPerformed

    private void rbChequeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbChequeActionPerformed
        resetNegro();
        setEntrego();
    }//GEN-LAST:event_rbChequeActionPerformed

    private void rbTransActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbTransActionPerformed
        resetNegro();
        setEntrego();
    }//GEN-LAST:event_rbTransActionPerformed

    private void txtEntregoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtEntregoMouseClicked
        txtEntrego.selectAll();
    }//GEN-LAST:event_txtEntregoMouseClicked

    private void rbEfectivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbEfectivoActionPerformed
        setEntrego();
    }//GEN-LAST:event_rbEfectivoActionPerformed

    private void movermePrecios(java.awt.event.KeyEvent evt) {
        switch(evt.getKeyCode()) {
            case 37:    //izq
                if (!evt.getComponent().getName().equals("txtNegro"))
                    txtNegro.requestFocus();
                break;
            case 38:    // arriba
                if (!evt.getComponent().getName().equals("txtDescuentoPie")
                    && !evt.getComponent().getName().equals("txtNegro") )
                    evt.getComponent().transferFocusBackward();
                break;
                
            case 39:    //dcha
                if (evt.getComponent().getName().equals("txtNegro"))
                    txtEntrego.requestFocus();     
                break;
            case 40:    // abajo
                if (!evt.getComponent().getName().equals("txtEntrego")
                    && !evt.getComponent().getName().equals("txtNegro") )
                    evt.getComponent().transferFocus();
                break;
        }
    }
    
    private void txtEntregoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtEntregoKeyReleased
        if (evt.getKeyCode() == 10) {
            if (ComprobarEntrego())
                bTicket.requestFocus();
        }
        else
            movermePrecios(evt);
        
    }//GEN-LAST:event_txtEntregoKeyReleased

    private void movermeBotones(java.awt.event.KeyEvent evt) {
        switch(evt.getKeyCode()) {
            case 37:    //izq
                if (!evt.getComponent().getName().equals("bImprimir"))
                    evt.getComponent().transferFocusBackward();
                break;
            case 38:    //arriba
                if (evt.getComponent().getName().equals("chPdf"))
                    bImprimir.requestFocus(true);
                break;
            case 39:    //dcha
                if (!evt.getComponent().getName().equals("bBorrar"))
                    evt.getComponent().transferFocus();     
                break;
            case 40:    //abajo
                if (!evt.getComponent().getName().equals("chPdf"))
                    chPdf.requestFocus(true);
                break;
        }
    }
    
    private void bGuardarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bGuardarKeyReleased
        movermeBotones(evt);
    }//GEN-LAST:event_bGuardarKeyReleased

    private void bTicketKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bTicketKeyReleased
        movermeBotones(evt);
    }//GEN-LAST:event_bTicketKeyReleased

    private void bImprimirKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bImprimirKeyReleased
        movermeBotones(evt);
    }//GEN-LAST:event_bImprimirKeyReleased

    private void bBorrarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bBorrarKeyReleased
        movermeBotones(evt);
    }//GEN-LAST:event_bBorrarKeyReleased

    private void txtNegroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNegroKeyReleased
        if(evt.getKeyCode() == 10) {
            if (txtEntrego.getText().isEmpty()) {
                txtEntrego.setText(txtNegro.getText());
                txtEntrego.requestFocus();
            }
            else { 
                if (ComprobarEntrego())
                   bTicket.requestFocus();
            }
        }
        else
            movermePrecios(evt);
    }//GEN-LAST:event_txtNegroKeyReleased

    private void chNoImpDescuentoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_chNoImpDescuentoKeyReleased
        movermePrecios(evt);
    }//GEN-LAST:event_chNoImpDescuentoKeyReleased

    private void chPdfKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_chPdfKeyPressed
        movermeBotones(evt);
    }//GEN-LAST:event_chPdfKeyPressed

    private void rbValeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbValeActionPerformed
        resetNegro();
        setEntrego();
    }//GEN-LAST:event_rbValeActionPerformed

    private void txtPrecioFinalManoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPrecioFinalManoFocusLost
        setPrecioFinal();
    }//GEN-LAST:event_txtPrecioFinalManoFocusLost

    private void txtEntregoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtEntregoFocusLost
        ComprobarEntrego();
    }//GEN-LAST:event_txtEntregoFocusLost

    private void bCajonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bCajonMouseClicked
        txtBuscar.requestFocus();
    }//GEN-LAST:event_bCajonMouseClicked

    private void cbVendedorItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbVendedorItemStateChanged
        ColorVendedor();
    }//GEN-LAST:event_cbVendedorItemStateChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bBorrar;
    private javax.swing.JButton bCajon;
    private javax.swing.JButton bGuardar;
    private javax.swing.JButton bImprimir;
    private javax.swing.JButton bListo;
    private javax.swing.JButton bTicket;
    private javax.swing.JComboBox cbTipoPago;
    private javax.swing.JComboBox cbTipoTicket;
    private javax.swing.JComboBox cbVendedor;
    private javax.swing.JCheckBox chNoImpDescuento;
    private javax.swing.JCheckBox chNoOriginal;
    private javax.swing.JCheckBox chPdf;
    private javax.swing.ButtonGroup grupo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField lblCant;
    private javax.swing.JTextField lblDesc;
    private javax.swing.JLabel lblDio;
    private javax.swing.JLabel lblError;
    private javax.swing.JTextField lblMarg;
    private javax.swing.JTextField lblQuitar;
    private javax.swing.JTextField lblResetear;
    private javax.swing.JLabel lblTime;
    private javax.swing.JPanel pBotones;
    private javax.swing.JPanel pCliente;
    private javax.swing.JPanel pDatosCliente;
    private javax.swing.JPanel pFecha;
    private javax.swing.JPanel pFinal;
    private javax.swing.JPanel pPago;
    private javax.swing.JPanel pPrecio;
    private javax.swing.JPanel pProductos;
    private javax.swing.JPanel pReloj;
    private javax.swing.JPanel pTipoTicket;
    private javax.swing.JRadioButton rbCheque;
    private javax.swing.JRadioButton rbEfectivo;
    private javax.swing.JRadioButton rbTarjeta;
    private javax.swing.JRadioButton rbTrans;
    private javax.swing.JRadioButton rbVale;
    private javax.swing.JTable tabla;
    public javax.swing.JTextField txtBuscar;
    private javax.swing.JLabel txtCantidad;
    private javax.swing.JButton txtCargarFactura;
    private javax.swing.JTextField txtCliCIF;
    private javax.swing.JTextField txtCliCodPostal;
    private javax.swing.JTextField txtCliDomicilio;
    private javax.swing.JTextField txtCliFiscal;
    private javax.swing.JTextField txtCliLocalidad;
    private javax.swing.JTextField txtCliNombre;
    private javax.swing.JTextField txtCliTelefono;
    public javax.swing.JTextField txtCodCliente;
    private javax.swing.JTextField txtComentario;
    private javax.swing.JTextField txtDescuentoPie;
    private javax.swing.JTextField txtEntrego;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtIdFecha;
    private javax.swing.JFormattedTextField txtIdImp;
    private javax.swing.JTextField txtNegro;
    public javax.swing.JTextField txtNomComercial;
    private javax.swing.JTextField txtNumCopias;
    private javax.swing.JTextField txtPrecioDigital;
    private javax.swing.JTextField txtPrecioFinal;
    private javax.swing.JTextField txtPrecioFinalMano;
    // End of variables declaration//GEN-END:variables
}
